<?php

namespace app\admin\controller;


use app\admin\model\AdminAccess as AccessModel;

use app\common\service\Result;

/**
 * 商家用户权限控制器
 */
class AdminAccess
{
    /**
     * 权限列表
     */
    public function index()
    {
        $model = new AccessModel();
        $parent_id = input('parent_id', 0);
        $list = $model->getList($parent_id);
        return Result::success($list);
    }

    /**
     * 添加权限
     */
    public function add()
    {
        $model = new AccessModel();
        $data = input();

        if ($model->add($data)) {
            return Result::success(compact('model'), "添加成功");
        }
        return Result::error($model->getError() ?: '添加失败');
    }

    /**
     * 更新权限
     */
    public function edit()
    {
        $data = input();
        $model = new AccessModel();
        // 权限详情
        $model = $model->find($data['access_id']);
        // 更新记录
        if ($model->edit($data)) {
            return Result::success("");
        }
        return Result::error($model->getError() ?: '更新失败');
    }

    /**
     * 删除权限
     */
    public function delete($access_id)
    {
        $model = new AccessModel();
        $num = $model->getChildCount(['parent_id' => $access_id]);
        if ($num > 0) {
            return Result::error('当前菜单下存在子权限，请先删除');
        }
        if ($model->remove($access_id)) {
            return Result::success();
        }
        return Result::error($model->getError() ?: '删除失败');
    }

    /**
     * 权限状态
     */
    public function status($access_id, $status)
    {
        $model = AccessModel::find($access_id);
        if ($model->status($status)) {
            return Result::success();
        }
        return Result::error($model->getError() ?: '修改失败');
    }

    public function role_menu()
    {
        $model = new AccessModel();
        $menus = $model->getList(0,1);
        return Result::success($menus);
    }
}